
/* globals svgEditor */
import { isValidUnit } from '../../common/units.js'
import imagePropertiesDialogHTML from './graphicEditor.html'


const template = document.createElement('template')
template.innerHTML = imagePropertiesDialogHTML
/**
 * @class SeImgPropDialog
 */
export class SegraphicEditor extends HTMLElement {
  /**
    * @function constructor
    */
  constructor() {
    super()
    // create the shadowDom and insert the template
    this._shadowRoot = this.attachShadow({ mode: 'open' })
    this._shadowRoot.append(template.content.cloneNode(true))
    this.$dialog = this._shadowRoot.querySelector('#svg_createment')
    this.$container  =  this._shadowRoot.querySelector('#container')
    this.$close  =  this._shadowRoot.querySelector('.close')


  }

  /**
   * @function init
   * @param {any} name
   * @returns {void}
   */
  init(i18next) {


  }

  /**
   * @function observedAttributes
   * @returns {any} observed
   */
  static get observedAttributes() {
    return ['dialog', 'common-ok', 'common-cancel','time-change','lib']
  }

  /**
   * @function attributeChangedCallback
   * @param {string} name
   * @param {string} oldValue
   * @param {string} newValue
   * @returns {void}
   */
  async attributeChangedCallback(name, oldValue, newValue) {
    if (oldValue === newValue) return
    switch (name) {
      case 'dialog':
        if (newValue === 'open') {
          this.$dialog.open()
          break
        } else {
          this.$dialog.close()
          break
        }
        break
        case 'lib':
           this.updateLib(newValue)
          break
      default:
        super.attributeChangedCallback(name, oldValue, newValue)
        break
    }
  }


  /**
   * @function get
   * @returns {any}
   */


  /**
   * @function get
   * @returns {any}
   */


  async updateLib (lib) {
    try {
      const response = await fetch(`${svgEditor.configObj.curConfig.serviceUrl}/svg/primitive/type/${lib}`)
      const json = await response.json()
      this.$container.innerHTML='';
      const svgCanvas = svgEditor.svgCanvas
      const { $id, $click ,$qq, $ } = svgCanvas
      var obj = json.data
      for(var key in obj){
        let title =obj[key]['title'];
        let content = obj[key]['content'];
        let id =obj[key]['id'];
        let  shap = decodeURIComponent(escape(atob(content)))
        const butTemplate  =`<se-button  id="${id}"  data-shap='${shap}' data-doc-type="${lib}"  title="${title}" src="data:image/svg+xml;base64,${content}" class="se-button"></se-button>`
        svgCanvas.insertChildAtIndex(this.$container, butTemplate)
        window.dataShap = '';
        window.docType  =  '';
        $(this.$container).on('click',"#"+id,function(){
            window.shapTitle = title
            window.dataShap = $(this).attr('data-shap');
            window.docType  =  $(this).attr('data-doc-type');
            const $imgDialog = $id('se-graphiceditor')
            $imgDialog.setAttribute('dialog', 'close')
          //  if(window.changePic){
          //   window.changePic = null
          //   svgEditor.elemAttrChangeCallBack({
          //     method: "samesizechange",
          //     mode: "DZ",
          //   })
          //  }
        })
      }


    } catch (error) {
      console.error(`could not read files:${lib}`, error)
    }
  }
  get dialog() {
    return this.getAttribute('dialog')
  }

  /**
   * @function set
   * @returns {void}
   */
  set dialog(value) {
    this.setAttribute('dialog', value)
  }

  /**
   * @function connectedCallback
   * @returns {void}
   */
  connectedCallback() {
    const {svgCanvas} = svgEditor

    const onCloselHandler = () => {
      const closeEvent = new CustomEvent('change', {
        detail: {
          dialog: 'closed'
        }
      })
      this.dispatchEvent(closeEvent)
    }

    svgEditor.$click(this.$close, onCloselHandler)

  }
}

// Register
customElements.define('se-graphiceditor-dialog', SegraphicEditor)
